﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace TaskTip
{
    public partial class Form_main : Form
    {
        public bool loading = true;      // 标识当前是否处于界面初始载入状态

        public Form_main()
        {
            InitializeComponent();
        }

        #region 界面初始载入与设置

        // 界面载入与显示逻辑
        private void Form_main_Load(object sender, EventArgs e)
        {
            comboBox_style.SelectedIndex = 1;   // 列表显示详细信息
            loadRegistrySetting();              // 载入配置信息
            setFunction();                      // 根据urlMode类型设置对应的功能逻辑
        }

        // 功能逻辑设置
        private void setFunction()
        {
            // 根据url类型，设置弹出快捷菜单显示
            任务状态ToolStripMenuItem.Visible = (loginForm.urlMode == 0);
            编辑ToolStripMenuItem.Visible = (loginForm.urlMode == 1);

            // 设置bug弹出快捷菜单显示
            解决ToolStripMenuItem.Visible = (loginForm.urlMode == 0);
            关闭ToolStripMenuItem.Visible = (loginForm.urlMode == 0);
            激活ToolStripMenuItem.Visible = (loginForm.urlMode == 0);
            编辑ToolStripMenuItem_Bug.Visible = (loginForm.urlMode == 1);

            // 根据url模式是否显示新增日志、审核、周报按钮
            //button_newLog.Visible = (loginForm.urlMode == 1);
            //button_performance.Visible = (loginForm.urlMode == 1);
            //button_weekLog.Visible = (loginForm.urlMode == 1);

            日志ToolStripMenuItem.Visible = (loginForm.urlMode == 1);
            周报ToolStripMenuItem.Visible = (loginForm.urlMode == 1);
            考核ToolStripMenuItem.Visible = (loginForm.urlMode == 1);
        }

        // 载入注册表设置的用户帐号密码信息
        private void loadRegistrySetting()
        {
            bool simpleMode = false;

            bool have = Tool.RegistryCotains(@"Scimence\TaskTip\Set");
            if (have)
            {
                String value = Tool.RegistryStrValue(@"Scimence\TaskTip\Set", "精简显示");
                if (value.Equals("true")) simpleMode = true;
            }
            else // 默认为精简模式
            {
                Tool.RegistrySave(@"Scimence\TaskTip\Set", "精简显示", "true");
                simpleMode = true;
            }

            checkBox_showMode.Checked = simpleMode; // 获取记录的显示模式信息
            loading = false;
        }

        // 设置listView的显示样式
        private void comboBox_style_SelectedIndexChanged(object sender, EventArgs e)
        {
            listView_opendBy.View = (View)comboBox_style.SelectedIndex;
            listView_assignedTo.View = (View)comboBox_style.SelectedIndex;
        }

        // 关闭当前界面
        private void button1_Click(object sender, EventArgs e)
        {
            loginForm.formMain = null;
            this.Close();
            loginForm.tipInTaskBar = false; // 关闭界面时，重置提示信息状态
        }

        #endregion

        #region 控制无边框窗体的显示与移动控制

        //using System.Runtime.InteropServices;  
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);

        private void Form_main_MouseDown(object sender, MouseEventArgs e)
        {
            //常量  
            int WM_SYSCOMMAND = 0x0112;

            //窗体移动  
            int SC_MOVE = 0xF010;
            int HTCAPTION = 0x0002;

            ReleaseCapture();
            SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }
        #endregion


        # region 界面信息显示逻辑


        //  定时刷新逻辑
        private void timer_main_Tick(object sender, EventArgs e)
        {
            updateShowing(); // 刷新显示
        }

        // 标识urls对应的数据是否有变动，是否需要刷新显示
        public static bool dataChanged = true;
        private bool loadingShowing = true;

        // 更新列表的显示信息
        private void updateShowing()
        {
            if (dataChanged) dataChanged = false;
            else return;

            ListView[] lists = { listView_assignedTo, listView_opendBy, listView_reviewedByMe, listView_myBug };
            bool simpleMode = checkBox_showMode.Checked;    // 是否以精简模式显示任务信息（仅显示任务名称和状态）

            //bool difStatusNULL = (loginForm.diffrentStatus == null);    // 初始时，不相同的任务状态为null
            for (int i = 0; i < loginForm.urls.Length; i++)
            {
                string url = loginForm.urls[i];
                string urlData = loginForm.webData[url];
                if (/*difStatusNULL ||*/ loadingShowing)                    // 若为初始载入，则刷新显示一次
                    showingData(lists[i], urlData, simpleMode);    
                else
                {
                    if (loginForm.diffrentStatus[url].Count > 0)         // 当前url有不相同的任务状态数据，则刷新显示
                        showingData(lists[i], urlData, simpleMode);
                }
            }

            loadingShowing = false;
        }

        // 在ListView中显示，特定格式的html数据信息
        private void showingData(ListView list, String data, bool simpleMode)
        {
            List<string> head = Tool.getHeads(data);    // 获取列表标题
            List<string[]> rows = Tool.getBodys(data);  // 获取列表信息

            Tool.setData(list, head, rows, simpleMode);             // 显示信息至列表
        }

        # endregion


        # region 修改任务状态信息
        // 修改任务状态信息

        private void MenuItem_wait_Click(object sender, EventArgs e)
        {
            postStatus("wait");
        }

        private void MenuItem_doing_Click(object sender, EventArgs e)
        {
            postStatus("doing");
        }

        private void MenuItem_done_Click(object sender, EventArgs e)
        {
            postStatus("done");
        }

        private void MenuItem_pause_Click(object sender, EventArgs e)
        {
            postStatus("pause");
        }

        private void MenuItem_cancel_Click(object sender, EventArgs e)
        {
            postStatus("cancel");
        }

        private void MenuItem_closed_Click(object sender, EventArgs e)
        {
            postStatus("closed");
        }

        // 字符串转化为整数
        private int toInt(string data, int defaltN)
        {
            try { return Int32.Parse(data); }
            catch (Exception) { return defaltN; }
        }

        // 发送任务状态信息到服务器
        private void postStatus(string status)
        {
            try
            {
                // 获取选中的任务信息
                ListView list = listView_assignedTo;
                if (tabControl_main.SelectedIndex == 1) list = listView_opendBy;
                else if (tabControl_main.SelectedIndex == 2) list = listView_reviewedByMe;
                else return;

                // 获取listView的列标题
                string[] header = (list.Columns.Count > 0 ? new string[list.Columns.Count] : null);
                for (int i = 0; i < list.Columns.Count; i++) header[i] = list.Columns[i].Text.Trim();
                List<string> Header = header.ToList<string>();

                foreach (ListViewItem iteam in list.SelectedItems) // 对所有选中的列表项执行操作
                {
                    string id = iteam.SubItems[Header.IndexOf("ID")].Text;                  // 选中的任务id
                    
                    string curDate = DateTime.Now.ToString("yyyy-MM-dd");
                    string closeReason = status.Equals("closed") ? "done" : "";

                    string consumed = iteam.SubItems[Header.IndexOf("消耗")].Text.Trim();  // 消耗

                    string left = iteam.SubItems[Header.IndexOf("剩")].Text;               // 剩
                    string deadline = iteam.SubItems[Header.IndexOf("截止")].Text;         // 截至日期
                    if (deadline.Equals("")) deadline = "0000-00-00";

                    // 生成请求信息
                    string url = "http://" + loginForm.serverIP + "/zentao/task-edit-" + id + ".html";
                    if (loginForm.urlMode == 1) url = "http://" + loginForm.serverIP + "/index.php?m=task&f=edit&taskID=" + id;
                    //postData = "name=test3&desc=&comment=&files[]=&labels[]=&consumed=100&project=1&module=0&story=&assignedTo=&type=devel&status=done&pri=0&mailto[]=&estStarted=0000-00-00&realStarted=2015-12-14&deadline=0000-00-00&estimate=0&left=100&finishedBy=&finishedDate=&canceledBy=&canceledDate=&closedBy=&closedReason=&closedDate=";
                    string postData = "";
                    // 已暂停、进行中post数据
                    if (status.Equals("pause") || status.Equals("doing"))  
                        postData = "consumed=" + consumed + "&status=" + status + "&estStarted=0000-00-00&realStarted=" + curDate + "&deadline=" + deadline + "&finishedBy=&finishedDate=&canceledBy=&canceledDate=&closedBy=&closedDate=&left=" + (left.Equals("0") ? "1" : left);  // 已暂停、进行中 无效
                    // 其他状态post数据
                    else postData = "consumed=" + consumed + "&status=" + status + "&estStarted=0000-00-00&realStarted=" + curDate + "&deadline=" + deadline + "&estimate=0&left=" + left + "&closedReason=" + closeReason;  // 已暂停、进行中 无效
                    

                    // 发送任务状态修改信息到服务器
                    string html = HttpTool.GetHtml(url, postData, Method.POST);

                    // 网页返回的提示信息
                    if (html.Contains("script") && html.Contains("alert"))
                    {
                        string info = Tool.getNode(html, "script");
                        info = info.Replace("alert(", "").Replace(")", "").Replace("'", "");
                        MessageBox.Show(info);
                    }
                    
                }

                // 手动刷新一次任务状态信息
                loginForm.UpdateData();
            }
            catch (Exception) { MessageBox.Show("任务状态提交异常！请重新提交"); }
        }

        # endregion

        // 双击选中的项目列表项时,打开对应项对应的网页
        private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListView list = (ListView)sender;
            for (int i = 0; i < list.SelectedItems.Count; i++)
            {
                string ID = list.SelectedItems[i].SubItems[i].Text;

                //string url = "http://" + serverIP + "/zentao/story-view-" + ID + ".html";
                string url = "http://" + loginForm.serverIP + "/zentao/task-view-" + ID + ".html";

                //http://10.80.3.12/index.php?m=project&f=view&projectID=11
                if (loginForm.urlMode == 1) url = "http://" + loginForm.serverIP + "/index.php?m=project&f=view&projectID=" + ID;
                HttpTool.openUrl(url);
            }
        }

        // 双击选中的项目列表项时,打开对应项对应的网页
        private void listView_MouseDoubleClick_Bug(object sender, MouseEventArgs e)
        {
            ListView list = (ListView)sender;
            for (int i = 0; i < list.SelectedItems.Count; i++)
            {
                string ID = list.SelectedItems[i].SubItems[i].Text;

                //string url = "http://" + serverIP + "/zentao/story-view-" + ID + ".html";
                //http://10.80.3.212/zentao/bug-view-73.html

                string url = "http://" + loginForm.serverIP + "/zentao/bug-view-" + ID + ".html";

                //http://10.80.3.12/index.php?m=bug&f=view&bugID=1
                if (loginForm.urlMode == 1) url = "http://" + loginForm.serverIP + "/index.php?m=bug&f=view&bugID=" + ID;
                HttpTool.openUrl(url);
            }
        }

        // http://10.80.3.212/zentao/bug-activate-78.html?onlybody=yes
        // http://10.80.3.212/zentao/bug-resolve-78.html?onlybody=yes 
        // http://10.80.3.212/zentao/bug-close-78.html?onlybody=yes 

        private void 解决ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String bugSate = "bug-resolve-";
            bugSate = "m=bug&f=resolve";
            openUrl_BugState(bugSate);
        }

        private void 关闭ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String bugSate = "bug-close-";
            bugSate = "m=bug&f=close";
            openUrl_BugState(bugSate);
        }

        private void 激活ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String bugSate = "bug-activate-";
            bugSate = "m=bug&f=activate";
            openUrl_BugState(bugSate);
        }

        // 打开Bug表选中项，对应状态的修改页
        private void openUrl_BugState(String bugSate)
        {
            // 发送任务状态信息到服务器
            try
            {
                // 获取选中的任务信息
                ListView list = listView_myBug;

                // 获取listView的列标题
                string[] header = (list.Columns.Count > 0 ? new string[list.Columns.Count] : null);
                for (int i = 0; i < list.Columns.Count; i++) header[i] = list.Columns[i].Text.Trim();
                List<string> Header = header.ToList<string>();

                foreach (ListViewItem iteam in list.SelectedItems) // 对所有选中的列表项执行操作
                {
                    string id = iteam.SubItems[Header.IndexOf("ID")].Text;                  // 选中的任务id

                    string url = "http://" + loginForm.serverIP + "/zentao/" + bugSate + id + ".html";
                    if (loginForm.urlMode == 1) url = "http://" + loginForm.serverIP + "/index.php?" + bugSate + "&taskID=" + id;
                    HttpTool.openUrl(url);
                }
            }
            catch (Exception) { MessageBox.Show("任务状态提交异常！请重新提交"); }
        }

        // 通知更新显示
        private void checkBox_showMode_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_showMode.Checked)
            {
                this.Width = 400;
                panel_main.Width = 400;
                tabControl_main.Width = 400;
            }
            else
            {
                this.Width = 1220;
                panel_main.Width = 1220;
                tabControl_main.Width = 1220;
            }

            if (loading) return;    // 若为初始载入中，则不更新

            // 记录显示模式信息
            String mode = checkBox_showMode.Checked ? "true" : "false";
            String value = Tool.RegistryStrValue(@"Scimence\TaskTip\Set", "精简显示");
            if (!mode.Equals(value)) Tool.RegistrySave(@"Scimence\TaskTip\Set", "精简显示", mode);

            dataChanged = true;
            loadingShowing = true;
        }


        ListView curSelectList;
        // 记录当前选中的listView列表
        private void listView_MouseClick_Record(object sender, MouseEventArgs e)
        {
            curSelectList = (ListView)sender;
        }

        // 列表项信息编辑
        private void 编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (curSelectList == null) return;
            for (int i = 0; i < curSelectList.SelectedItems.Count; i++)
            {
                string ID = curSelectList.SelectedItems[i].SubItems[i].Text;

                //string url = "http://" + serverIP + "/zentao/story-view-" + ID + ".html";
                string url = "http://" + loginForm.serverIP + "/zentao/task-edit-" + ID + ".html";

                //http://10.80.3.12/index.php?m=project&f=edit&projectID=11
                //if (loginForm.urlMode == 1) url = "http://" + loginForm.serverIP + "/index.php?m=project&f=edit&projectID=" + ID;

                //http://10.80.3.12/index.php?m=task&f=edit&taskID=2
                if (loginForm.urlMode == 1) url = "http://" + loginForm.serverIP + "/index.php?m=task&f=edit&taskID=" + ID;
                HttpTool.openUrl(url);
            }
        }

        // bug信息编辑
        private void 编辑ToolStripMenuItem_Bug_Click(object sender, EventArgs e)
        {
            if (curSelectList == null) return;
            for (int i = 0; i < curSelectList.SelectedItems.Count; i++)
            {
                string ID = curSelectList.SelectedItems[i].SubItems[i].Text;
                string url = "http://" + loginForm.serverIP + "/zentao/bug-edit-" + ID + ".html";

                //http://10.80.3.12/index.php?m=bug&f=edit&bugID=1
                if (loginForm.urlMode == 1) url = "http://" + loginForm.serverIP + "/index.php?m=bug&f=edit&bugID=" + ID;
                HttpTool.openUrl(url);
            }
        }

        // 打开新增日志界面
        private void button_newLog_Click(object sender, EventArgs e)
        {
            //http://10.80.3.12/index.php?m=effort&f=batchCreate&date=20160504

            String curDate = DateTime.Today.ToString("yyyyMMdd");
            String url = "http://" + loginForm.serverIP + "/index.php?m=effort&f=batchCreate&date=" + curDate;
            HttpTool.openUrl(url);
        }

        // 打开考核界面
        private void button_performance_Click(object sender, EventArgs e)
        {
            //http://task.joymeng.com/index.php?m=my&f=performance
            String url = "http://" + loginForm.serverIP + "/index.php?m=my&f=performance";
            HttpTool.openUrl(url);
        }

        // 打开周报界面
        private void button_weekLog_Click(object sender, EventArgs e)
        {
            //http://task.joymeng.com/index.php?m=my&f=weekly
            String url = "http://" + loginForm.serverIP + "/index.php?m=my&f=weekly";
            HttpTool.openUrl(url);
        }

    }
}
